<template>
  <div class="pass-rate-chart">
    <div class="chart-header">
      <h3>抽检合格率统计</h3>
      <el-button size="small" @click="refreshChart">刷新</el-button>
    </div>
    <div ref="chartContainer" class="chart" style="height: 400px;"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { listResults } from '@/api/quality-service/results'

const props = defineProps({
  // 可以接收外部传入的数据
  resultsData: {
    type: Array,
    default: () => []
  },
  // 是否自动刷新
  autoRefresh: {
    type: Boolean,
    default: true
  },
  // 刷新间隔(秒)
  refreshInterval: {
    type: Number,
    default: 60
  }
})

const chartContainer = ref(null)
let chartInstance = null
let refreshTimer = null

// 计算合格率
const calculatePassRate = (data) => {
  // 按工单ID分组
  const groupedByOrder = data.reduce((acc, item) => {
    if (!acc[item.orderId]) {
      acc[item.orderId] = []
    }
    acc[item.orderId].push(item)
    return acc
  }, {})

  // 计算每个工单的合格率
  const result = Object.keys(groupedByOrder).map(orderId => {
    const items = groupedByOrder[orderId]
    const passCount = items.filter(item =>
        item.defectDescription && item.defectDescription.trim() === '无'
    ).length
    const passRate = (passCount / items.length) * 100

    return {
      orderId,
      passRate: parseFloat(passRate.toFixed(2)),
      sampleCount: items.length,
      date: items[0]?.inspectionTime || new Date().toISOString()
    }
  })

  // 按日期排序
  return result.sort((a, b) => new Date(a.date) - new Date(b.date))
}

// 获取数据并更新图表
const fetchDataAndUpdateChart = async () => {
  try {
    // 如果外部传入数据，则使用外部数据
    if (props.resultsData && props.resultsData.length > 0) {
      updateChart(props.resultsData)
      return
    }

    // 否则从API获取数据
    const response = await listResults({
      pageNum: 1,
      pageSize: 1000 // 获取足够多的数据
    })

    const processedData = response.rows.map(item => ({
      ...item,
      imageUrls: item.defectImageUrl ? item.defectImageUrl.split(',') : []
    }))

    updateChart(processedData)
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

// 更新图表
const updateChart = (data) => {
  if (!chartInstance) return

  const passRateData = calculatePassRate(data)

  const option = {
    title: {
      text: '抽检合格率趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: params => {
        const data = params[0].data
        return `工单ID: ${data.orderId}<br/>
                合格率: ${data.passRate}%<br/>
                样本数量: ${data.sampleCount}<br/>
                日期: ${data.date}`
      }
    },
    xAxis: {
      type: 'category',
      data: passRateData.map(item => item.orderId),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [
      {
        name: '合格率',
        type: 'line',
        data: passRateData.map(item => ({
          value: item.passRate,
          orderId: item.orderId,
          sampleCount: item.sampleCount,
          date: item.date
        })),
        markLine: {
          silent: true,
          data: [
            {
              type: 'average',
              name: '平均值',
              label: {
                position: 'end',
                formatter: '平均值: {c}%'
              }
            }
          ]
        },
        itemStyle: {
          color: '#409EFF'
        },
        lineStyle: {
          width: 3
        },
        symbolSize: 8
      }
    ],
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100
      }
    ]
  }

  chartInstance.setOption(option, true)
}

// 初始化图表
const initChart = () => {
  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(chartContainer.value)
  window.addEventListener('resize', resizeChart)
  fetchDataAndUpdateChart()
}

// 刷新图表
const refreshChart = () => {
  fetchDataAndUpdateChart()
}

// 响应式调整图表大小
const resizeChart = () => {
  chartInstance?.resize()
}

// 设置自动刷新
const setupAutoRefresh = () => {
  if (props.autoRefresh) {
    clearInterval(refreshTimer)
    refreshTimer = setInterval(() => {
      fetchDataAndUpdateChart()
    }, props.refreshInterval * 1000)
  }
}

// 监听props变化
watch(() => props.resultsData, (newVal) => {
  if (newVal && newVal.length > 0) {
    updateChart(newVal)
  }
}, { deep: true })

// 生命周期钩子
onMounted(() => {
  initChart()
  setupAutoRefresh()
})

onBeforeUnmount(() => {
  if (chartInstance) {
    window.removeEventListener('resize', resizeChart)
    chartInstance.dispose()
    chartInstance = null
  }
  clearInterval(refreshTimer)
})
</script>

<style scoped>
.pass-rate-chart {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-top: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.chart {
  width: 100%;
}
</style>